package nio.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

//服务器端
public class NioServer {
    public static void main(String[] args) throws IOException {
        //得到选择器
        Selector selector = Selector.open();
        //监听通道
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        //绑定端口
        socketChannel.socket().bind(new InetSocketAddress(6666));
        //设置为非阻塞
        socketChannel.configureBlocking(false);
        //监听通道注册到选择器   关心事件 OP_ACCEPT
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //循环等待客户端连接
        while (true) {
            //等待1秒无连接，返回
            if (selector.select(1000) == 0) {
                System.out.println("超时1秒，无连接。");
                continue;
            }
            //返回大于0 获取相关的SelectionKey集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //遍历集合
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                //根据key对应的通道发生的事件对应处理
                if (key.isAcceptable()) {//有新的连接
                    //为该客户端生成通道
                    SocketChannel channel = socketChannel.accept();
                    channel.configureBlocking(false);
                    //注册到选择器
                    channel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    System.out.println("SelectionKey数量===" + selector.keys().size());//注册的key
                    System.out.println("selectedKeys数量===" + selector.selectedKeys().size());//有事件的key
                }
                if (key.isReadable()) {//已连接 读事件
                    SocketChannel readChannel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
                    readChannel.read(byteBuffer);
                    System.out.println("读取客户端" + new String(byteBuffer.array()));
                }
                //手动删除 防止重复
                keyIterator.remove();

            }
        }
    }
}
